#include "squaresurface.h"
#include "functions.h"

// ======================================================================================
// Square surface intersection
// ======================================================================================
float SquareSurface::SurfaceIntersection(const Ray& ray) {
    // -- compute the sides and find the normal
    Vector4 side1 = Normalize(square.v1 - square.v0);
    Vector4 side2 = Normalize(square.v2 - square.v0);
    float radians = acos(DotProduct(side1, side2));
    if(radians < kPi/2)
        return 0.0f;

    Vector4 normal = CrossProduct(side1, side2);

    if(normal.z < 0.0f)
        return 0.0f;

    // -- compute d of the plane
    float d1 = -(DotProduct(normal, ray.origin));
    float d = d1 + (DotProduct(normal, square.v0));
    float denom = (DotProduct(normal, ray.direction));
    float t = d/denom;

    Vector4 dest = ray.ComputeRay(t);

    if(dest.z > 0.0f) 
        return 0.0f;

    Vector4 result = dest - square.v0;

    float project1 = DotProduct(result, side1);
    float project2 = DotProduct(result, side2);

    if(project1 > square.width || project2 > square.height)
        return 0.0f;

    if(project1 < 0.0f || project2 < 0.0f)
        return 0.0f;

    // -- return the scalar value
    return t;
}
